import { View, Text, ScrollView, Image } from '@tarojs/components'
import { useState, useEffect, useRef } from 'react'
import Taro from '@tarojs/taro'
import { API_BASE_URL } from '../../../config/env'
import imageCacheManager from '../../utils/imageCache'

const HospitalCard = ({ hospital, onClick }) => {
  const [logoLoaded, setLogoLoaded] = useState(false)
  const [logoError, setLogoError] = useState(false)
  const [logoLocalUrl, setLogoLocalUrl] = useState(null) // 医院logo本地缓存
  const [productImagesLoaded, setProductImagesLoaded] = useState({})
  const [productImagesError, setProductImagesError] = useState({})
  const [productImagesLocalUrl, setProductImagesLocalUrl] = useState({}) // 产品图片本地缓存
  const logoTimeoutRef = useRef(null)
  const productTimeoutsRef = useRef({})
  const maxRetries = 1 // 减少重试次数，快速失败

  // 备用图片URL
  const fallbackLogo = 'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=100&h=100&fit=crop'
  const fallbackProductImage = 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300&h=200&fit=crop'
  
  // 处理图片URL，将相对路径转换为完整URL
  const getFullImageUrl = (imageUrl) => {
    console.log('🏥 医院图片原始URL:', imageUrl)
    console.log('🌐 API_BASE_URL:', API_BASE_URL)
    
    if (!imageUrl) {
      console.log('❌ 医院图片URL为空，使用备用图片')
      return fallbackLogo
    }
    
    // 处理完整URL，包括localhost替换
    if (imageUrl.startsWith('http')) {
      // 检查是否包含localhost，如果是则替换为API_BASE_URL
      if (imageUrl.includes('localhost') || imageUrl.includes('127.0.0.1')) {
        const path = imageUrl.replace(/^https?:\/\/[^\/]+/, '')
        const newUrl = `${API_BASE_URL}${path}`
        console.log('🔄 医院图片检测到localhost，替换为API_BASE_URL:', newUrl)
        return newUrl
      }
      console.log('✅ 医院图片检测到完整URL，直接使用:', imageUrl)
      return imageUrl
    }
    
    const fullUrl = imageUrl.startsWith('/') 
      ? `${API_BASE_URL}${imageUrl}`
      : `${API_BASE_URL}/${imageUrl}`
    
    console.log('🔗 医院图片拼接后的完整URL:', fullUrl)
    return fullUrl
  }

  // 重置logo加载状态
  useEffect(() => {
    setLogoLoaded(false)
    setLogoError(false)
    
    // 移除超时机制，让图片自然加载
    console.log('🏥 开始加载医院logo:', hospital.logo)
    
    return () => {
      if (logoTimeoutRef.current) {
        clearTimeout(logoTimeoutRef.current)
      }
    }
  }, [hospital.logo])

  const handleLogoLoad = () => {
    setLogoLoaded(true)
    setLogoError(false)
    console.log('✅ 医院logo加载成功:', hospital.logo)
  }

  // 智能降级：下载图片到本地
  const downloadImageToLocal = async (imageUrl, type = 'logo', productId = null) => {
    try {
      console.log('🔄 开始下载图片到本地:', imageUrl, type)
      const downloadResult = await Taro.downloadFile({
        url: imageUrl,
        timeout: 10000
      })
      
      if (downloadResult.statusCode >= 200 && downloadResult.statusCode < 300 && downloadResult.tempFilePath) {
        console.log('✅ 图片下载成功:', downloadResult.tempFilePath)
        
        if (type === 'logo') {
          setLogoLocalUrl(downloadResult.tempFilePath)
          setLogoError(false)
          setLogoLoaded(false) // 重置加载状态
        } else if (type === 'product' && productId) {
          setProductImagesLocalUrl(prev => ({ ...prev, [productId]: downloadResult.tempFilePath }))
          setProductImagesError(prev => ({ ...prev, [productId]: false }))
          setProductImagesLoaded(prev => ({ ...prev, [productId]: false })) // 重置加载状态
        }
        return true
      } else {
        throw new Error(`下载失败，状态码: ${downloadResult.statusCode}`)
      }
    } catch (error) {
      console.error('❌ 图片下载失败:', error)
      return false
    }
  }

  const handleLogoError = async () => {
    console.log('❌ 医院logo加载失败，尝试下载到本地:', hospital.logo)
    const downloadSuccess = await downloadImageToLocal(getFullImageUrl(hospital.logo), 'logo')
    
    if (!downloadSuccess) {
      // 下载也失败，显示失败状态
      setLogoError(true)
      setLogoLoaded(false)
      console.log('💥 医院logo加载和下载都失败')
    }
  }

  const handleProductImageLoad = (productId) => {
    setProductImagesLoaded(prev => ({ ...prev, [productId]: true }))
    setProductImagesError(prev => ({ ...prev, [productId]: false }))
    console.log('✅ 医院产品图片加载成功:', productId, '图片URL:', hospital.products.find(p => p.id === productId)?.image)
  }

  const handleProductImageError = async (productId, originalUrl) => {
    console.log('❌ 医院产品图片加载失败，尝试下载到本地:', productId, originalUrl)
    const downloadSuccess = await downloadImageToLocal(getFullImageUrl(originalUrl), 'product', productId)
    
    if (!downloadSuccess) {
      // 下载也失败，显示失败状态
      setProductImagesError(prev => ({ ...prev, [productId]: true }))
      setProductImagesLoaded(prev => ({ ...prev, [productId]: false }))
      console.log('💥 医院产品图片加载和下载都失败:', productId)
    }
  }

  const handleClick = () => {
    if (onClick) {
      onClick(hospital)
    }
  }

  const handleConsultClick = (e) => {
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation()
    }
    // 跳转到聊天页，可按需携带医院ID/名称
    const hospitalId = hospital.id || hospital._id || ''
    const hospitalName = encodeURIComponent(hospital.name || '')
    const query = `?targetType=hospital&targetId=${hospitalId}&targetName=${hospitalName}`
    console.log('consult tap -> navigateTo', `/pages/chat/chat${query}`)
    Taro.navigateTo({ url: `/pages/chat/chat${query}` })
      .catch(() => {
        // 兜底：若 navigateTo 异常，尝试 redirectTo
        Taro.redirectTo({ url: `/pages/chat/chat${query}` }).catch(() => {
          Taro.showToast({ title: '无法打开聊天页', icon: 'none' })
        })
      })
  }

  return (
    <View className='hospital-card' onClick={handleClick}>
      {/* 医院头部信息 */}
      <View className='hospital-header'>
        <View className='hospital-info'>
          <View className='logo-container'>
            {!logoLoaded && !logoError && (
              <View className='logo-loading'>
                <Text>加载中...</Text>
              </View>
            )}
            {!logoError ? (
              <Image 
                className={`hospital-logo ${logoLoaded ? 'loaded' : ''}`}
                src={logoLocalUrl || getFullImageUrl(hospital.logo)}
                mode='aspectFill'
                onLoad={handleLogoLoad}
                onError={handleLogoError}
                lazyLoad
              />
            ) : (
              <View className='logo-placeholder'>
                <View className='placeholder-icon'>🏥</View>
                <View className='placeholder-text'>医院</View>
              </View>
            )}
          </View>
          <View className='hospital-details'>
            <Text className='hospital-name'>{hospital.name}</Text>
            <View className='hospital-stats'>
              <Text className='rating'>⭐ {hospital.rating ? hospital.rating.toFixed(1) : '0.0'}</Text>
              <Text className='services'>
                {hospital.city && hospital.location ? `${hospital.city} · ${hospital.location}` : 
                 hospital.city || hospital.location || '未知位置'}
              </Text>
            </View>
          </View>
        </View>
        <View className='hospital-actions'>
          <View className='consult-btn' onTap={handleConsultClick}>私信咨询</View>
        </View>
      </View>
      
      {/* 医院标签 */}
      {hospital.tag && (
        <View className='hospital-tag'>
          <Text>{hospital.tag}</Text>
        </View>
      )}
      
      {/* 医院产品列表 - 水平滚动 */}
      <View className='hospital-products-container'>
        {hospital.products && hospital.products.length > 0 ? (
          <ScrollView 
            className='hospital-products-scroll'
            scrollX
            showScrollbar={false}
            enhanced
            scrollWithAnimation
          >
            <View className='hospital-products-list'>
              {hospital.products.map((product) => {
            const productId = product.id || product._id
            const isImageLoaded = productImagesLoaded[productId]
            const isImageError = productImagesError[productId]
            
            // 移除超时机制，让图片自然加载
            useEffect(() => {
              if (product.image && !isImageLoaded && !isImageError) {
                console.log('🏥 开始加载产品图片:', productId, product.image)
              }
            }, [productId, product.image, isImageLoaded, isImageError])
            
            return (
              <View key={productId} className='hospital-product-card'>
                <View className='product-image-container'>
                  {!isImageLoaded && !isImageError && (
                    <View className='product-image-loading'>
                      <Text>加载中...</Text>
                    </View>
                  )}
                  <Image 
                    className={`product-image ${isImageLoaded ? 'loaded' : ''}`}
                    src={isImageError ? fallbackProductImage : (productImagesLocalUrl[productId] || getFullImageUrl(product.image))}
                    mode='aspectFill'
                    onLoad={() => handleProductImageLoad(productId)}
                    onError={() => handleProductImageError(productId, product.image)}
                    lazyLoad
                  />
                </View>
                <Text className='product-title'>{product.title}</Text>
                {/* 产品标签 */}
                {product.tags && product.tags.length > 0 && (
                  <View className='product-tags'>
                    {product.tags.slice(0, 2).map((tag, index) => (
                      <Text key={index} className='product-tag'>{tag}</Text>
                    ))}
                  </View>
                )}
                <View className='product-price'>
                  <Text className='current-price'>¥{product.price}</Text>
                  {product.saved > 0 && <Text className='saved-price'>已省¥{product.saved}</Text>}
                </View>
              </View>
            )
          })}
            </View>
          </ScrollView>
        ) : (
          <View className='no-products'>
            <Text>暂无产品信息</Text>
          </View>
        )}
      </View>
    </View>
  )
}

export default HospitalCard
